import { ref, onMounted, toRaw } from "vue";
import { WalletConnector } from "@/utils/wallet";
import { ethers } from "ethers";
import {
  showSuccessToast,
  showFailToast,
  closeToast,
  showLoadingToast,
} from "vant";
import BigNumber from "bignumber.js";
import ERC20 from "@/utils/contractABI/erc20";
import Miner from "@/utils/contractABI/Miner";
import { showToast } from "vant";
// 连接钱包
export function useConWallet() {
  // 获取当前账号
  const account = ref<string | null>(null);
  // 获取当前 provider
  const provider = ref<any>(null);
  // 获取当前 signer
  const signer = ref<any>(null);
  // 组件挂载时检查钱包是否已经连接
  onMounted(async () => {
    const connected = await WalletConnector.connectWallet();
    if (connected) {
      account.value = WalletConnector.getAccount();
      provider.value = WalletConnector.getProvider();
      signer.value = WalletConnector.getSigner();
    }
  });

  const connectWallet = async () => {
    const connected = await WalletConnector.connectWallet();
    if (connected) {
      account.value = WalletConnector.getAccount();
      provider.value = WalletConnector.getProvider();
      signer.value = WalletConnector.getSigner();
    }
  };
  // 根据选中的代币类型选择对应的合约地址和 ABI
  // const getTokenDetails = (selectedToken) => {
  //   console.log(selectedToken, "selectedToken");
  //   switch (selectedToken) {
  //     case "USDT":
  //       // return { address: import.meta.env.VITE_USDT_ADRESS, abi: ERC20 };
  //       return { abi: ERC20 };
  //     case "BNB":
  //       // 对于 BNB，返回一个特定的对象，或者仅返回 null
  //       return { address: null, abi: null };
  //     default:
  //       throw new Error("Unknown token type");
  //   }
  // };
  // 燃油代币转账
  const transfer = async (to: string, amount: number) => {
    // signer会变成proxy对象，但是ethers有要求，必须是原对象，所以需要toRaw进行转化成原对象
    const signers = toRaw(signer.value);
    try {
      const tx = await signers.sendTransaction({
        to,
        value: ethers.utils.parseEther(amount.toString()),
      });
      await tx.wait();
      showSuccessToast("充值成功！");
      return tx.hash;
    } catch (error) {
      showFailToast("充值失败!");
      console.log("Error sending transaction:", error.transactionHash);
      return error.expectedHash;
    }
  };
  // ERC20代币转账
  const transferErc = async (to: string, num: string) => {
    try {
      // 验证输入参数
      if (!to || !ethers.utils.isAddress(to)) {
        throw new Error("Invalid recipient address");
      }
      if (isNaN(num) || num <= 0) {
        throw new Error("Invalid transfer amount");
      }
      const signers = toRaw(signer.value);
      // 验证 signer 是否有效
      if (!signers || !signers.provider) {
        throw new Error("Signer not initialized");
      }
      // 转换金额为最小单位 (考虑18位小数)
      const amount = new BigNumber(num).times(1e18).toFixed(0);
      // 调用智能合约的ERC20-USDT
      const usdtContract = new ethers.Contract(
        import.meta.env.VITE_USDT_ADRESS,
        ERC20,
        signers
      );
      // 开始交易转账,要设置燃油费区间，要不然计算不出来
      const tx = await usdtContract.transfer(to, amount, {
        gasLimit: 300000,
      });
      showLoadingToast({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      // 等待交易确认
      await tx.wait();
      showToast("充值成功");
      closeToast();
      console.log(tx.hash, "receipt.hash");

      return tx.hash; // 返回交易哈希 tx
    } catch (error) {
      showToast("充值失败");
      return error.expectedHash;
    }
  };

  // 购买算力合约逻辑
  const BuyPowerTransfer = async (num: string, parentAddress: string) => {
    try {
      const signers = toRaw(signer.value);
      // 验证 signer 是否有效
      if (!signers || !signers.provider) {
        throw new Error("Signer not initialized");
      }
      // 转换金额为最小单位 (考虑18位小数)
      const amount = new BigNumber(num).times(1e18).toFixed(0);

      // 调用智能合约的ERC20-USDT
      const usdtContract = new ethers.Contract(
        import.meta.env.VITE_USDT_ADRESS,
        ERC20,
        signers
      );
      // 调用智能合约的ERC20-USDT
      const MinerContract = new ethers.Contract(
        import.meta.env.VITE_MINER_ADRESS,
        Miner,
        signers
      );
      try {
        // 进行授权safeApprove
        const approve = await usdtContract.approve(
          import.meta.env.VITE_MINER_ADRESS,
          amount
        );
        if (approve.hash) {
          console.log("====================================");
          console.log(approve.hash);
          console.log("====================================");
          // 开始交易转账,要设置燃油费区间，要不然计算不出来
          const tx = await MinerContract.deposit(amount, parentAddress);
          showLoadingToast({
            message: "加载中...",
            forbidClick: true,
            loadingType: "spinner",
            duration: 0,
          });
          // 等待交易确认
          await tx.wait();
          closeToast();
          console.log(tx.hash, "receipt.hash");
          return tx.hash; // 返回交易哈希 tx
        }
      } catch (err) {
        closeToast();
        console.error(err);
      }
    } catch (err) {}
  };

  return { account, transfer, transferErc, BuyPowerTransfer };
}
